package com.acwing.partition13;

import java.io.*;
import java.util.*;

/**
 * @author `RKC`
 * @date 2022/3/9 10:48
 */
public class AC1234倍数问题_dp贪心 {

    private static final int N = 1010, INF = 0x3f3f3f3f;
    private static Map<Integer, List<Integer>> rmap = new HashMap<>(N);
    private static int[][] f = new int[4][N];
    private static int n, k;

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        String[] ss = reader.readLine().split(" ");
        n = Integer.parseInt(ss[0]);
        k = Integer.parseInt(ss[1]);
        ss = reader.readLine().split(" ");
        for (int i = 0; i < N; i++) rmap.put(i, new ArrayList<>());
        //把余数相同的数都放在一组里面
        for (int i = 1; i <= n; i++) {
            int num = Integer.parseInt(ss[i - 1]);
            rmap.get(num % k).add(num);
        }
        for (int i = 0; i < f.length; i++) {
            for (int j = 0; j < f[i].length; j++) {
                Arrays.fill(f[i], -INF);
            }
        }
        f[0][0] = 0;
        //枚举每一组余数
        for (int i = 0; i < k; i++) {
            //对这组余数从大到小排序，从中选择最大的3个做背包问题
            List<Integer> list = rmap.get(i % k);
            list.sort((o1, o2) -> Integer.compare(o2, o1));
            for (int u = 0; u < Math.min(3, list.size()); u++) {
                for (int j = 3; j >= 1; j--) {
                    for (int x = 0; x < k; x++) {
                        f[j][x] = Math.max(f[j][x], f[j - 1][getMod(x - list.get(u), k)] + list.get(u));
                    }
                }
            }
        }
        writer.write(f[3][0] + "\n");
        writer.flush();
    }

    private static int getMod(int a, int b) {
        return (a % b + b) % b;
    }
}
